/*
 * @Author: szx
 * @Date: 2022-03-16 14:03:24
 * @LastEditTime: 2022-03-16 14:13:35
 * @Description:
 * @FilePath: \leetcode\1000-1099\1005\1005_2.js
 */
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var largestSumAfterKNegations = function (nums, k) {
    nums.sort((a, b) => Math.abs(a) - Math.abs(b));
    let res = 0;
    for (let i = nums.length - 1; i >= 0; i--) {
        if (nums[i] < 0 && k > 0) {
            nums[i] = -nums[i];
            k--;
        }
        res += nums[i];
    }
    if (k & 1) res += -nums[0] * 2;
    return res;
};
console.log(largestSumAfterKNegations([2, -3, -1, 5, -4], 2));
console.log(largestSumAfterKNegations([3, -1, 0, 2], 3));
console.log(largestSumAfterKNegations([4, 2, 3], 1));
